﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Framework.Library.Components.Portal;
using Framework.Library.Components.Commands;
using Framework.Library.Components.Security;
using Framework.Library.Components.Users;
using Framework.Library.Utilities;
using Framework.Library;

namespace Portal.Administrator.Users
{
	public partial class UserPermision : AuthenticatedControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            if ((!CurrentUser.IsSuperAdmin && CommandController.IsSystemModule(AppEnv.CommandID())) || !CommandController.IsAvailableForUser(AppEnv.CommandID(), CurrentUser.UserID, Convert.ToInt32(AppEnv.PortalId())))
                Response.Redirect(AppEnv.ADMIN_CMD, true);			
			if (!Page.IsPostBack)
			{
                LoadPortal();				
                lblCommandName.Text = AppEnv.CommandName();
			}
		}

        public void LoadPortal()
        {
            //Fill portals
            dropPortal.Items.Clear();
            PortalController.LoadPortalsForUserID(dropPortal.Items, CurrentUser.UserID);
            dropPortal.SelectedValue = AppEnv.PortalId();
            LoadUser();
        }
        public void LoadUser()
        {
            dropUser.Items.Clear();
            UserController.LoadUser(dropUser.Items, ConvertUtility.ToInt32(dropPortal.SelectedValue));
            dropUser.SelectedValue = CurrentUser.UserID.ToString();
            BindData();
        }
        public void BindData()
        {            
            lstCommands.Items.Clear();
            CommandController.FillToListBox(lstCommands.Items, CommandController.GetCommands(), CurrentUser.IsSuperAdmin);

            DataTable dtUserCommands = CommandController.GetCommandsForUserNotGroup(ConvertUtility.ToInt32(dropUser.SelectedValue), ConvertUtility.ToInt32(dropPortal.SelectedValue));
            foreach (DataRow row in dtUserCommands.Rows)
            {
                if (lstCommands.Items.FindByValue(row["CommandID"].ToString()) != null)
                    lstCommands.Items.FindByValue(row["CommandID"].ToString()).Selected = true;
            }
            LoadCommandInfo(dtUserCommands);
        }
        private void LoadCommandInfo(DataTable dtUserCommands)
        {
            DataTable dtReturnCommand = new DataTable();
            dtReturnCommand.Columns.Add("CommandID", typeof(String));
            dtReturnCommand.Columns.Add("CommandKey", typeof(String));
            dtReturnCommand.Columns.Add("PortalID", typeof(String));
            dtReturnCommand.Columns.Add("UserID", typeof(String));
            dtReturnCommand.Columns.Add("CommandParentID", typeof(String));
            dtReturnCommand.Columns.Add("CommandName", typeof(String));
            dtReturnCommand.Columns.Add("Level", typeof(String));
            dtReturnCommand.Columns.Add("Role_View", typeof(String));
            dtReturnCommand.Columns.Add("Role_Add", typeof(String));
            dtReturnCommand.Columns.Add("Role_Update", typeof(String));
            dtReturnCommand.Columns.Add("Role_Delete", typeof(String));
            DataTable _dtReturnCommand = UserController.BuildRecursiveUserPermission(dtUserCommands, dtReturnCommand, ConvertUtility.ToInt32(dropUser.SelectedValue), ConvertUtility.ToInt32(dropPortal.SelectedValue));
            dgrUserRole.DataSource = _dtReturnCommand;
            dgrUserRole.DataBind();

        }
		
		protected void btnUpdate_Click(object sender, EventArgs e)
		{
			try
			{
				foreach (ListItem item in lstCommands.Items)
				{
					if (item.Selected)
					{
                        UserController.AddCommandToUserByPortalID(Convert.ToInt32(item.Value), ConvertUtility.ToInt32(dropUser.SelectedValue), ConvertUtility.ToInt32(dropPortal.SelectedValue));
					}
					else
					{
                        UserController.RemoveCommandFromUserByPortalID(Convert.ToInt32(item.Value), ConvertUtility.ToInt32(dropUser.SelectedValue), ConvertUtility.ToInt32(dropPortal.SelectedValue));
					}
				}
                BindData();
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
               
			}
			catch (Exception ex)
			{
                lblUpdateStatus.Text = ex.Message;
			}
		}
        protected void dgrUserRole_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "edit")
            {
                int user_id = ConvertUtility.ToInt32(e.Item.Cells[0].Text);
                int command_id = ConvertUtility.ToInt32(e.Item.Cells[1].Text);
                int portal_id = ConvertUtility.ToInt32(e.Item.Cells[2].Text);
                CheckBox chkView = (CheckBox)e.Item.FindControl("chkView");
                CheckBox chkAdd = (CheckBox)e.Item.FindControl("chkAdd");
                CheckBox chkUpdate = (CheckBox)e.Item.FindControl("chkEdit");
                CheckBox chkDelete = (CheckBox)e.Item.FindControl("chkDelete");
                try
                {
                    UserController.UpdateUserPermissionByPortalID(user_id, command_id, portal_id, chkView.Checked, chkAdd.Checked, chkUpdate.Checked, chkDelete.Checked);
                    DataTable dtUserCommands = CommandController.GetCommandsForUserNotGroup(ConvertUtility.ToInt32(dropUser.SelectedValue), ConvertUtility.ToInt32(dropPortal.SelectedValue));
                    LoadCommandInfo(dtUserCommands);
                    lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                }
                catch(Exception ex)
                {
                    lblUpdateStatus.Text = ex.Message;
                }
            }
        }
        protected void dgrUserRole_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemIndex < 0) return;

            DataRowView row = (DataRowView)e.Item.DataItem;
            ImageButton btnUpdate = (ImageButton)e.Item.FindControl("btnUpdate");            

            Label lblCmdName = (Label)e.Item.FindControl("lblCmdName");
            lblCmdName.Text = row["CommandName"].ToString();

            CheckBox chkView = (CheckBox)e.Item.FindControl("chkView");
            CheckBox chkAdd = (CheckBox)e.Item.FindControl("chkAdd");
            CheckBox chkEdit = (CheckBox)e.Item.FindControl("chkEdit");
            CheckBox chkDelete = (CheckBox)e.Item.FindControl("chkDelete");

            if (!String.IsNullOrEmpty(row["CommandKey"].ToString()))
            {
                chkView.Checked = ConvertUtility.ToBoolean(row["Role_View"].ToString());
                chkAdd.Checked = ConvertUtility.ToBoolean(row["Role_Add"].ToString());
                chkEdit.Checked = ConvertUtility.ToBoolean(row["Role_Update"].ToString());
                chkDelete.Checked = ConvertUtility.ToBoolean(row["Role_Delete"].ToString());
            }
            else
            {
                chkAdd.Visible = false;
                chkDelete.Visible = false;
                chkEdit.Visible = false;
                chkView.Visible = false;
                btnUpdate.Visible = false;
            }            
        }

        protected void btnUpdateAll_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridItem item in dgrUserRole.Items)
                {
                    int user_id = ConvertUtility.ToInt32(item.Cells[0].Text);
                    int command_id = ConvertUtility.ToInt32(item.Cells[1].Text);
                    int portal_id = ConvertUtility.ToInt32(item.Cells[2].Text);
                    CheckBox chkView = (CheckBox) item.FindControl("chkView");
                    CheckBox chkAdd = (CheckBox) item.FindControl("chkAdd");
                    CheckBox chkUpdate = (CheckBox) item.FindControl("chkEdit");
                    CheckBox chkDelete = (CheckBox) item.FindControl("chkDelete");
                    UserController.UpdateUserPermissionByPortalID(user_id, command_id, portal_id, chkView.Checked, chkAdd.Checked, chkUpdate.Checked, chkDelete.Checked);
                }
                DataTable dtUserCommands = CommandController.GetCommandsForUserNotGroup(ConvertUtility.ToInt32(dropUser.SelectedValue), ConvertUtility.ToInt32(dropPortal.SelectedValue));
                LoadCommandInfo(dtUserCommands);
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
            }
            catch
            {
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_ERROR;
            }
        }        

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            lstCommands.SelectedIndex = -1;
        }

        protected void dropPortal_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadUser();
        }

        protected void dropUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindData();
        }
	}
}